#include "DefFile.h"
using namespace std;

boost::dynamic_bitset<> LFSRpolL1 ;
boost::dynamic_bitset<> LFSRpolL2 ;
boost::dynamic_bitset<> LFSRpolL3 ;

long file_size(const char* file_name){
	long begin ,end;
	ifstream lfr_file(file_name);
	begin=lfr_file.tellg();
	lfr_file.seekg(0, ios::end);
	end=lfr_file.tellg();
	lfr_file.close();
	return end-begin;
}
boost::dynamic_bitset<>* GetLFSFfromFile(const char * file_name){
	size_t s=file_size(file_name);
	boost::dynamic_bitset <> *lfsr_z= new boost::dynamic_bitset<>(s);
	ifstream file;
	file.open(file_name);
	char x;
	if (file.is_open()){
		for (boost::dynamic_bitset<>::size_type i=0;(i<lfsr_z->size())&&(file.good());++i){
			file.get(x);
			(*lfsr_z)[i]=(bool) (x - 48);
		}
		file.close();
	}
	else cout << "Unable to open file LFR.txt/n";
	return lfsr_z;
}
double CalculateQuantile(double A, const char* file_name){
	A=double(1-A)*100;
	//cout<<setprecision(15)<<"A = "<<A<<endl;
	double t=double();
	ifstream file (file_name);
	int cnt_r=int();
	if(file.is_open()){
		while( !file.eof() ) if( file.get() == '\n' ) cnt_r++;
	}else cout<<"Unable to open file "<<file_name<<endl;
	cnt_r++;

	double** Quantile=new double* [cnt_r];
	for (int i=0;i<cnt_r;++i)
		Quantile[i]=new double	[2];
	string str;
	file.close();file.open(file_name);
	if(file.is_open()){
		for (int i=0;(i<cnt_r)&&(file.good());++i){
			file>>str;
			Quantile[i][0]=atof(str.c_str());
			file>>str;
			Quantile[i][1]=atof(str.c_str());
		}
		file.close();
	}else cout<<"Unable to open file "<<file_name<<endl;
	double delta=1,cur=0;int pos=int();
	for (int i = 0; i < cnt_r; ++i)
	{
		cur=abs(A-Quantile[i][0]);
		if (cur<delta){ delta=cur;pos=i;}
	}
	t=Quantile[pos][1];
	for (int i = 0; i < cnt_r; ++i)
	{
		delete[] Quantile[i];
	}
	delete[] Quantile;
	return t;
}